import React, { useState, useEffect } from 'react';
import { ck_empty, KSelect, Info, obj_int, loc, ck_int, useKForm, KDlg, KInput } from 'sui';
import { load_ng } from 'test/base/cmd';
import { is_box } from './cmd';

const DlgNum = (props) => {
    const [lst_ngson, lstNg] = useState();
    const form = useKForm(props.data);

    useEffect(() => {
        if (!props.open) {
            return;
        }

        load_ng(lstNg, null, props.mod);
    }, [props.open, props.mod]);

    const is_ng = () => props.fin === "ng";

    const ck = {
        num: v => {
            const e = ck_int(v);
            if (e) {
                return e;
            }

            const tmp = parseInt(v, 10);
            const num = obj_int(props.data, "num");

            if (tmp > num) {
                return loc("l_707");
            }

            if (is_box(props.mod)) {
                const count = obj_int(form.value, "snum") * obj_int(form.value, "box");
                if (tmp !== count) {
                    return loc("l_110");
                }
            }

            return null;
        },
    };

    if (is_box(props.mod)) {
        ck["snum"] = v => ck_int(v);
        ck["box"] = v => ck_int(v);
    }

    if (is_ng()) {
        ck["ngson"] = v => ck_empty(v);
    }

    const getTitle = () => {
        if (is_ng()) {
            return loc("l_107");
        }

        return loc("l_106");
    };

    const getNg = () => {
        if (is_ng()) {
            return <KSelect label={loc("l_811")} form={form} name="ngson" lst={lst_ngson} className="mt-2"/>;
        }

        return null;
    };

    const getView = () => {
        if (is_box(props.mod)) {
            return (
                <>
                <KInput label={loc("l_452")} form={form} name="box"/>
                <KInput label={loc("l_108")} form={form} name="snum"/>
                </>
            );
        }

        return null;
    };

    return (
        <KDlg {...props} title={getTitle()} ck={ck} form={form}>
            <Info data={props.data} col={props.col} hl={["num"]}/>
            <KInput label={loc("l_127")} form={form} name="num"/>
            {getView()}
            {getNg()}
        </KDlg>
    );
};

export {DlgNum};
